<template>
  <div class="label-tree">
    <div class="toolbar">
      <el-input v-model="q" size="small" placeholder="搜索标签" />
      <el-button type="primary" size="small" @click="showCreateDialog" :icon="Plus">添加标签</el-button>
    </div>
    <el-tree 
      :data="tree" 
      node-key="id" 
      :props="{ children: 'children', label: 'name' }" 
      @node-click="onSelect" 
      default-expand-all
    >
      <template #default="{ data }">
        <div class="tree-node">
          <span class="swatch" :style="{ backgroundColor: data.color || '#ddd' }"></span>
          <span class="label-name">{{ data.name }}</span>
          <span v-if="labelStats[data.id] > 0" class="label-count">({{ labelStats[data.id] }})</span>
          <div class="node-actions">
            <el-button type="text" size="small" @click.stop="editLabel(data)" :icon="Edit"></el-button>
            <el-button type="text" size="small" @click.stop="deleteLabel(data)" :icon="Delete" :disabled="labelStats[data.id] > 0"></el-button>
          </div>
        </div>
      </template>
    </el-tree>

    <!-- 创建/编辑标签对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="editingLabel ? '编辑标签' : '创建标签'"
      width="400px"
    >
      <el-form :model="labelForm" label-width="80px">
        <el-form-item label="标签名称" required>
          <el-input v-model="labelForm.name" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="颜色">
          <div class="color-picker-container">
            <el-color-picker v-model="labelForm.color" />
            <span class="color-preview" :style="{ backgroundColor: labelForm.color || '#ddd' }"></span>
          </div>
        </el-form-item>
        <el-form-item label="父级标签">
          <el-select v-model="labelForm.parent_id" placeholder="选择父级标签（可选）" clearable>
            <el-option
              v-for="label in availableParents"
              :key="label.id"
              :label="label.name"
              :value="label.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="labelForm.description" type="textarea" placeholder="标签描述（可选）" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="labelForm.sort" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveLabel" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useLabelsStore, type Label } from '../store/labels'
import { useAnnoStore } from '../store/anno'
import { useApi } from '../api'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete, Plus } from '@element-plus/icons-vue'

const store = useLabelsStore()
const anno = useAnnoStore()
const q = ref('')
const tree = computed(()=> store.filteredTree(q.value))
const api = useApi()

// 对话框状态
const dialogVisible = ref(false)
const editingLabel = ref<Label | null>(null)
const saving = ref(false)

// 表单数据
const labelForm = ref({
  name: '',
  color: '#409eff',
  parent_id: null as string | null,
  description: '',
  sort: 0
})

// 计算每个标签的使用次数
const labelStats = computed(() => {
  const stats: Record<string, number> = {}
  // 遍历所有标注，统计每个 label_id 的使用次数
  for (const annotation of anno.list) {
    const labelId = annotation.label_id
    stats[labelId] = (stats[labelId] || 0) + 1
  }
  return stats
})

// 可用的父级标签（排除当前编辑的标签及其后代）
const availableParents = computed(() => {
  let labels = store.items
  if (editingLabel.value) {
    // 排除当前标签及其后代
    const excludeIds = new Set([editingLabel.value.id])
    const findChildren = (parentId: string) => {
      for (const label of store.items) {
        if (label.parent_id === parentId && !excludeIds.has(label.id)) {
          excludeIds.add(label.id)
          findChildren(label.id)
        }
      }
    }
    findChildren(editingLabel.value.id)
    labels = labels.filter(l => !excludeIds.has(l.id))
  }
  return labels
})

onMounted(async ()=>{
  await loadLabels()
})

async function loadLabels() {
  try {
    const res = await api.getLabels()
    if(res?.data){
      store.setItems(res.data)
    }
  } catch (error) {
    ElMessage.error('加载标签失败')
  }
}

function onSelect(node:any){
  store.setCurrent(node)
}

function showCreateDialog() {
  editingLabel.value = null
  labelForm.value = {
    name: '',
    color: '#409eff',
    parent_id: null,
    description: '',
    sort: 0
  }
  dialogVisible.value = true
}

function editLabel(label: Label) {
  editingLabel.value = label
  labelForm.value = {
    name: label.name,
    color: label.color || '#409eff',
    parent_id: label.parent_id || null,
    description: label.description || '',
    sort: label.sort || 0
  }
  dialogVisible.value = true
}

async function saveLabel() {
  if (!labelForm.value.name.trim()) {
    ElMessage.error('请输入标签名称')
    return
  }

  saving.value = true
  try {
    const payload = {
      name: labelForm.value.name.trim(),
      color: labelForm.value.color,
      parent_id: labelForm.value.parent_id,
      description: labelForm.value.description,
      sort: labelForm.value.sort
    }

    if (editingLabel.value) {
      // 更新标签
      await api.updateLabel(editingLabel.value.id, payload)
      store.updateItem({ ...editingLabel.value, ...payload })
      ElMessage.success('标签更新成功')
    } else {
      // 创建标签
      const res = await api.createLabel(payload)
      if (res?.data?.id) {
        store.addItem({ id: res.data.id, ...payload })
        ElMessage.success('标签创建成功')
      }
    }
    
    dialogVisible.value = false
  } catch (error) {
    ElMessage.error(editingLabel.value ? '更新标签失败' : '创建标签失败')
  } finally {
    saving.value = false
  }
}

async function deleteLabel(label: Label) {
  if (labelStats.value[label.id] > 0) {
    ElMessage.warning('该标签已被使用，无法删除')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要删除标签"${label.name}"吗？`, '确认删除', {
      type: 'warning'
    })
    
    await api.deleteLabel(label.id)
    store.removeItem(label.id)
    ElMessage.success('标签删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除标签失败')
    }
  }
}
</script>
<style scoped>
.label-tree { 
  padding: 8px; 
}

.toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  align-items: center;
}

.toolbar .el-input {
  flex: 1;
}

.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  padding-right: 8px;
}

.swatch { 
  width: 12px; 
  height: 12px; 
  border-radius: 3px; 
  display: inline-block; 
  border: 1px solid rgba(0,0,0,0.1); 
  margin-right: 6px; 
  vertical-align: middle; 
  flex-shrink: 0;
}

.label-name { 
  vertical-align: middle; 
  flex: 1;
}

.label-count { 
  color: #666; 
  font-size: 12px; 
  margin-left: 4px; 
  vertical-align: middle;
  flex-shrink: 0;
}

.node-actions {
  opacity: 0;
  transition: opacity 0.2s;
  display: flex;
  gap: 2px;
  margin-left: 8px;
  flex-shrink: 0;
}

.tree-node:hover .node-actions {
  opacity: 1;
}

.color-picker-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.color-preview {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  border: 1px solid rgba(0,0,0,0.1);
  display: inline-block;
}

:deep(.el-tree-node__content) {
  height: auto;
  padding: 4px 0;
}

:deep(.el-tree-node__content:hover) {
  background-color: var(--el-tree-node-hover-bg-color);
}
</style>
